package leetcode.medium.q18;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Solution().fourSum(new int[]{1, 0, -1, 0, -2, 2}, -0));
        System.out.println(new Solution().fourSum(new int[]{1000000000, 1000000000, 1000000000, 1000000000}
                , -294967296));
        //-2 -1 0 0 1 2
    }
}

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i - 1 >= 0 && nums[i] == nums[i - 1]) continue;
            if ((long) nums[i] + nums[i + 2] + nums[i + 1] + nums[i + 3] > target) break;
            if ((long) nums[i] + nums[nums.length - 2] + nums[nums.length - 1] + nums[nums.length - 3] < target)
                continue;
//            System.out.println(1+"i:"+i);
            for (int j = i + 1; j < nums.length - 2; j++) {
                if ((long) nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
                int m = j + 1, n = nums.length - 1;
                if (j - 1 > i && nums[j] == nums[j - 1]) continue;
//                System.out.println(2);
                while (m < n) {
                    if (m - 1 >= j + 1 && nums[m] == nums[m - 1]) {
                        m++;
                        continue;
                    }
//                    System.out.println(3);
                    long sum = (long) nums[i] + nums[j] + nums[n] + nums[m];
                    if (sum == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[m++], nums[n--]));
                    } else if (sum < target) m++;
                    else if (sum > target) n--;
                }

            }
        }
        return res;
    }
}
